﻿using System;
using System.Text.RegularExpressions;
using mmCore.Common;

namespace mmSubProvider
{
    public class SubDownload
    {
        #region MEMBERS

        private int _mEpisode;

        #endregion MEMBERS

        #region EVENTS

        public event Action<SubSearchResult,string> OnSubtitleAvailable;

        #endregion EVENTS

        #region METHODS

        public void SubtitleAvailable(SubSearchResult movie, int season, int episode)
        {
            var wfMovie = new WebFetch(SubUtils.GetMovieUrl(movie.Id, season));
            wfMovie.OnFinished += OnMovieDetailsFinished;
            _mEpisode = episode;
            wfMovie.Fetch(movie);
        }

        #endregion METHODS

        #region PRIVATE

        private void OnMovieDetailsFinished(object sender, FetchEventArgs e)
        {
            var movie = e.Data as SubSearchResult;

            if (movie == null)
            {
                if (OnSubtitleAvailable != null)
                {
                    OnSubtitleAvailable(movie, string.Empty);
                }
                return;
            }

            var strReg = string.Format("<td>[\\d]*?x{0}</td>[\\d\\D]*?<nobr><a href=\"([\\d\\D]*?).html\"><img src=\"images/flags/en.gif\"", SubUtils.AddZero(_mEpisode));

            try
            {
                var rRegex = new Regex(strReg, RegexOptions.Multiline);
                var mMatch = rRegex.Match(e.Result);

                if (mMatch.Success)
                {
                    var subIdUrl = mMatch.Groups[1].Value;

                    if (subIdUrl.Contains("subtitle"))
                    {
                        var subId = subIdUrl.Substring("subtitle-".Length);
                        if (OnSubtitleAvailable != null)
                        {
                            OnSubtitleAvailable(movie, SubUtils.GetSubtitleUrl(subId));
                        }
                    }
                    else
                    {
                        ProcessEpisodeSubtitles(movie, subIdUrl);
                    }
                }
                else
                {
                    if (OnSubtitleAvailable != null)
                    {
                        OnSubtitleAvailable(movie, string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.ReportError(ex);
                if (OnSubtitleAvailable != null)
                {
                    OnSubtitleAvailable(movie, string.Empty);
                }
            }
        }

        private void ProcessEpisodeSubtitles(SubSearchResult movie, string me)
        {
            var wf = new WebFetch(string.Format("http://www.tvsubtitles.net/{0}.html", me));
            wf.OnFinished += wf_OnFinished;
            wf.Fetch(movie);
        }

        private void wf_OnFinished(object sender, FetchEventArgs e)
        {
            const string strReg = "<a href=\"/subtitle-([\\d]*?).html[\\d\\D]*?(\\d)*?</p></div></a>";
            var rRegex = new Regex(strReg, RegexOptions.Multiline);
            var mMatch = rRegex.Match(e.Result);

            var nMaxDownloads = 0;
            var strBestId = string.Empty;

            if (!mMatch.Success)
            {
                if (OnSubtitleAvailable != null)
                {
                    OnSubtitleAvailable(e.Data as SubSearchResult, string.Empty);
                }
                return;
            }

            while (mMatch.Success)
            {
                var nSubId = mMatch.Groups[1].Value;
                var nDownloads = Int32.Parse(mMatch.Groups[2].Value);
                if (nDownloads > nMaxDownloads)
                {
                    nMaxDownloads = nDownloads;
                    strBestId = nSubId;
                }
                mMatch = mMatch.NextMatch();
            }

            if (OnSubtitleAvailable != null)
            {
                OnSubtitleAvailable(e.Data as SubSearchResult, SubUtils.GetSubtitleUrl(strBestId));
            }
        }

        #endregion PRIVATE
    }
}
